<template>
  <div class="app-container">
    <div class="top-right-btns">
      <el-button plain size="small" icon="el-icon-back" @click="goBack">返回列表</el-button>
      <el-button v-show="activeName === 'basic'" type="primary" size="small" @click="submitForm">{{ form.id ? '修改' : '新增' }}</el-button>
    </div>

    <el-tabs v-model="activeName" class="main-tabs">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="form.productName" placeholder="请输入产品名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品分类" prop="deviceType">
                <el-select v-model="form.deviceType" placeholder="请选择产品分类">
                  <el-option v-for="dict in dict.type.iot_device_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备类型" prop="deviceCategory">
                <el-select v-model="form.deviceType" placeholder="请选择设备类型">
                  <el-option v-for="dict in dict.type.iot_device_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通讯协议" prop="commProtocol">
                <el-select v-model="form.commProtocol" placeholder="请选择通讯协议">
                  <el-option v-for="dict in dict.type.iot_comm_protocol" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="传输协议" prop="transProtocol">
                <el-select v-model="form.transProtocol" placeholder="请选择传输协议">
                  <el-option v-for="dict in dict.type.iot_trans_protocol" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联网方式" prop="networkMethod">
                <el-select v-model="form.networkMethod" placeholder="请选择联网方式">
                  <el-option v-for="dict in dict.type.iot_network_method" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="启用授权" prop="isAuthRequired">
                <el-radio-group v-model="form.isAuthRequired">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品编号" prop="id">
                <el-input v-model="form.id" placeholder="系统自动生成" readonly/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="MQTT账号" prop="mqttAccount">
                <el-input v-model="form.mqttAccount" placeholder="请输入MQTT账号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="MQTT密码" prop="mqttPassword">
                <el-input v-model="form.mqttPassword" placeholder="请输入MQTT密码" show-password/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="产品密钥" prop="productKey">
                <el-input v-model="form.productKey" placeholder="请输入产品密钥" show-password/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="产品图片" prop="productImage">
            <image-upload v-model="form.productImage"/>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 物模型相关内容 -->
      <el-tab-pane label="产品模型" name="model" :disabled="!form.id">
        <div class="model-container">
          <div class="model-header">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-button size="small" type="primary" plain icon="el-icon-plus" @click="handleAddModel">新增</el-button>
                <el-button size="small" type="success" plain icon="el-icon-upload2" @click="handleImportModel">导入通用物模型</el-button>
                <el-button size="small" type="info" plain icon="el-icon-refresh" @click="loadModelList">刷新</el-button>
              </el-col>
            </el-row>
          </div>
          <el-table :data="modelList" style="width: 100%">
            <el-table-column prop="modelName" label="名称"/>
            <el-table-column prop="modelCode" label="标识符"/>
            <el-table-column prop="modelType" label="物模型类别">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.modelType === 'property'" type="primary">属性</el-tag>
                <el-tag v-else-if="scope.row.modelType === 'function'" type="success">功能</el-tag>
                <el-tag v-else-if="scope.row.modelType === 'event'" type="warning">事件</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="实时监测">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.isRealtime === '1'" type="success">是</el-tag>
                <el-tag v-else type="info">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="只读数据">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.isReadonly === '1'" type="success">是</el-tag>
                <el-tag v-else type="info">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="历史存储">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.isHistory === '1'" type="success">是</el-tag>
                <el-tag v-else type="info">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="dataType" label="数据类型">
              <template slot-scope="scope">
                <span v-if="scope.row.dataType === 'int'">整数型</span>
                <span v-else-if="scope.row.dataType === 'float'">小数型</span>
                <span v-else-if="scope.row.dataType === 'bool'">布尔型</span>
                <span v-else-if="scope.row.dataType === 'string'">字符串</span>
                <span v-else-if="scope.row.dataType === 'enum'">枚举型</span>
                <span v-else>{{scope.row.dataType}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditModel(scope.row)">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteModel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 设备授权 -->
      <el-tab-pane label="设备授权" name="auth" :disabled="!form.id">
        <div class="auth-container">
          <div class="auth-header">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-input v-model="authQuery.keyword" placeholder="请输入授权码或设备编号" clearable>
                  <el-button slot="append" icon="el-icon-search" @click="searchAuth"/>
                </el-input>
              </el-col>
              <el-col :span="8">
                <el-button type="primary" icon="el-icon-plus" @click="handleAddAuth">新增</el-button>
                <el-button type="success" icon="el-icon-download" @click="handleExportAuth">导出</el-button>
              </el-col>
            </el-row>
          </div>
          <el-table :data="authList" style="width: 100%">
            <el-table-column prop="authCode" label="授权码"/>
            <el-table-column prop="deviceCode" label="设备编号"/>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.status === 1">已使用</el-tag>
                <el-tag v-else>未使用</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="authTime" label="授权时间" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.authTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteAuth(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 使用物模型表单组件 -->
    <model-form
      ref="modelForm"
      :title="modelTitle"
      :visible.sync="modelOpen"
      @submit="submitModelForm"
    />

    <!-- 导入物模型对话框 -->
    <el-dialog title="导入通用物模型" :visible.sync="importOpen" width="900px" append-to-body>
      <div class="model-search">
        <el-form :model="importQuery" ref="importQueryForm" :inline="true">
          <el-form-item label="模型名称">
            <el-input v-model="importQuery.name" placeholder="请输入物模型名称" clearable size="small"/>
          </el-form-item>
          <el-form-item label="模型类别">
            <el-select v-model="importQuery.type" placeholder="请选择模型类别" clearable size="small">
              <el-option label="属性" value="property"/>
              <el-option label="功能" value="function"/>
              <el-option label="事件" value="event"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="searchImportModel">搜索</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetImportQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="importModelList" @selection-change="handleImportSelectionChange" height="400">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="modelName" label="名称" show-overflow-tooltip/>
        <el-table-column prop="modelCode" label="标识符" show-overflow-tooltip/>
        <el-table-column prop="modelType" label="物模型类别" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.modelType === 'property'" type="primary" size="small">属性</el-tag>
            <el-tag v-else-if="scope.row.modelType === 'function'" type="success" size="small">功能</el-tag>
            <el-tag v-else-if="scope.row.modelType === 'event'" type="warning" size="small">事件</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dataType" label="数据类型" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.dataType === 'int'">整数型</span>
            <span v-else-if="scope.row.dataType === 'float'">小数型</span>
            <span v-else-if="scope.row.dataType === 'bool'">布尔型</span>
            <span v-else-if="scope.row.dataType === 'string'">字符串</span>
            <span v-else-if="scope.row.dataType === 'enum'">枚举型</span>
            <span v-else>{{scope.row.dataType}}</span>
          </template>
        </el-table-column>
        <el-table-column label="实时监测" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isRealtime === '1'" type="success" size="small">是</el-tag>
            <el-tag v-else type="info" size="small">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="只读数据" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isReadonly === '1'" type="success" size="small">是</el-tag>
            <el-tag v-else type="info" size="small">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="历史存储" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isHistory === '1'" type="success" size="small">是</el-tag>
            <el-tag v-else type="info" size="small">否</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmImport" :disabled="importSelection.length === 0">确 定</el-button>
        <el-button @click="cancelImport">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getProduct, addProduct, updateProduct, listCommonModel } from "@/api/iot/product";
import { addModel, listModel, listProductModel, delProductModel } from "@/api/iot/model";
import ModelForm from "@/components/IoT/ModelForm";
import request from '@/utils/request'

// 添加产品模型关联关系
function addProductModelRel(data) {
  return request({
    url: '/iot/product/model',
    method: 'post',
    data: data
  })
}

export default {
  name: "ProductForm",
  components: {
    ModelForm
  },
  dicts: ['sys_yes_no', 'iot_device_type', 'iot_trans_protocol', 'iot_auth_method', 'iot_comm_protocol', 'iot_network_method'],
  data() {
    return {
      // 是否已创建产品
      isCreated: false,
      // 选中的标签页
      activeName: 'basic',
      // 表单参数
      form: {
        id: null,
        productName: null,
        deviceType: null,
        deviceCategory: null,
        commProtocol: null,
        transProtocol: null,
        networkMethod: null,
        isAuthRequired: 0,
        authMethod: null,
        productCode: null,
        mqttAccount: null,
        mqttPassword: null,
        productKey: null,
        productImage: null,
        remark: null
      },
      // 物模型查询参数
      modelQuery: {
        type: null,
        isHistory: null
      },
      // 物模型列表数据
      modelList: [],
      // 授权查询参数
      authQuery: {
        keyword: null
      },
      // 授权列表数据
      authList: [],
      // 表单校验规则
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        deviceType: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        commProtocol: [
          { required: true, message: "通讯协议不能为空", trigger: "change" }
        ],
        transProtocol: [
          { required: true, message: "传输协议不能为空", trigger: "change" }
        ],
        networkMethod: [
          { required: true, message: "联网方式不能为空", trigger: "change" }
        ],
        authMethod: [
          { required: true, message: "认证方式不能为空", trigger: "change" }
        ]
      },
      // 物模型对话框标题
      modelTitle: "",
      // 是否显示物模型对话框
      modelOpen: false,
      // 导入物模型对话框标题
      importTitle: "",
      // 是否显示导入物模型对话框
      importOpen: false,
      // 导入物模型查询参数
      importQuery: {
        name: null,
        type: null
      },
      // 导入物模型列表数据
      importModelList: [],
      // 导入物模型选择数据
      importSelection: []
    };
  },
  created() {
    // 获取路由中的ID参数
    const id = this.$route.query.id;
    if (id) {
      // 如果有ID，说明是修改操作，获取详情
      this.getInfo(id);
    } else {
      // 如果没有ID，说明是新增操作，重置表单
      this.reset();
    }
  },
  methods: {
    /** 获取产品详细信息 */
    getInfo(id) {
      getProduct(id).then(response => {
        // 将后端返回的数据直接赋值给表单
        this.form = response.data;
        // 设置已创建标志，使页签可用
        this.isCreated = true;
        // 如果启用授权，加载授权列表
        if (this.form.isAuthRequired === 1) {
          this.loadAuthList();
        }
        // 加载物模型列表
        this.loadModelList();
      });
    },
    /** 重置表单数据 */
    reset() {
      this.form = {
        id: undefined,
        productName: undefined,
        deviceType: undefined,
        deviceCategory: undefined,
        commProtocol: undefined,
        transProtocol: undefined,
        networkMethod: undefined,
        isAuthRequired: 0,
        authMethod: undefined,
        mqttAccount: undefined,
        mqttPassword: undefined,
        productKey: undefined,
        productImage: undefined,
        remark: undefined
      };
      this.resetForm("form");
      this.modelList = [];
      this.authList = [];
      this.isCreated = false;
      this.activeName = 'basic';
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.goBack();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.form.id = response.data.id;
              this.isCreated = true;
            });
          }
        }
      });
    },
    /** 物模型相关方法 */
    handleAddModel() {
      this.modelTitle = "添加物模型";
      this.modelOpen = true;
      // 重置表单数据
      this.$nextTick(() => {
        this.$refs.modelForm.resetForm();
        // 设置产品ID
        this.$refs.modelForm.form.productId = this.form.id;
      });
    },
    /** 编辑物模型 */
    handleEditModel(row) {
      this.modelTitle = "修改物模型";
      this.modelOpen = true;
      // 在下一个事件循环中设置表单数据，确保表单已经被重置
      this.$nextTick(() => {
        this.$refs.modelForm.form = { ...row };
      });
    },
    /** 删除物模型 */
    handleDeleteModel(row) {
      this.$modal.confirm('是否确认删除该物模型？').then(() => {
        delProductModel(this.form.id, row.id).then(response => {
          this.$modal.msgSuccess("删除成功");
          this.loadModelList();
        });
      }).catch(() => {});
    },
    /** 提交物模型表单 */
    submitModelForm(formData) {
      // 确保带上产品ID
      formData.productId = this.form.id;
      // 转换布尔值字段
      formData.isReadonly = formData.isReadonly === '1';
      formData.isMonitor = formData.isRealtime === '1';
      formData.isHistory = formData.isHistory === '1';
      
      // 确保必要字段存在
      const submitData = {
        productId: formData.productId,
        modelName: formData.name,          // 模型名称
        modelCode: formData.identifier,    // 模型标识
        modelType: formData.type,          // 模型类别
        dataType: formData.dataType,       // 数据类型
        dataDefine: formData.dataDefine,   // 数据定义
        isMonitor: formData.isMonitor,     // 是否实时监测
        isReadonly: formData.isReadonly,   // 是否只读
        isHistory: formData.isHistory,     // 是否历史存储
        modelSort: formData.sort || 1      // 模型排序
      };

      // 调用后端API添加物模型
      addModel(submitData).then(response => {
        this.$modal.msgSuccess("新增成功");
        this.modelOpen = false;
        // 重新加载物模型列表
        this.loadModelList();
      });
    },
    /** 导入物模型按钮操作 */
    handleImportModel() {
      this.importOpen = true;
      this.importSelection = [];
      this.searchImportModel();
    },
    /** 搜索导入物模型 */
    searchImportModel() {
      listCommonModel(this.importQuery).then(response => {
        this.importModelList = response.rows.map(item => ({
          ...item,
          isRealtime: item.isRealtime ? '1' : '0',
          isReadonly: item.isReadonly ? '1' : '0',
          isHistory: item.isHistory ? '1' : '0'
        }));
      });
    },
    /** 确认导入物模型 */
    confirmImport() {
      if (this.importSelection.length === 0) {
        this.$modal.msgError("请选择要导入的物模型");
        return;
      }

      // 使用 Promise.all 处理多个模型的导入
      const importPromises = this.importSelection.map(model => {
        const submitData = {
          productId: this.form.id,
          modelId: model.id
        };
        return addProductModelRel(submitData);
      });

      Promise.all(importPromises)
        .then(() => {
          this.$modal.msgSuccess("导入成功");
          this.importOpen = false;
          // 重新加载物模型列表
          this.loadModelList();
        })
        .catch(error => {
          this.$modal.msgError("导入失败：" + error.message);
        });
    },
    /** 设备授权相关方法 */
    searchAuth() {
      // TODO: 实现搜索授权的逻辑
    },
    handleAddAuth() {
      // TODO: 实现新增授权的逻辑
    },
    handleExportAuth() {
      // TODO: 实现导出授权的逻辑
    },
    handleDeleteAuth(row) {
      // TODO: 实现删除授权的逻辑
    },
    /** 加载授权列表 */
    loadAuthList() {
      // TODO: 实现加载授权列表的逻辑
    },
    /** 加载物模型列表 */
    loadModelList() {
      listProductModel(this.form.id).then(response => {
        // 转换布尔值为字符串，用于显示，并映射字段名称
        this.modelList = response.rows.map(item => ({
          ...item,
          name: item.modelName,           // 显示名称
          identifier: item.modelCode,     // 标识符
          type: item.modelType,           // 类型
          sort: item.modelSort,           // 排序
          isRealtime: item.isMonitor ? '1' : '0',   // 实时监测
          isReadonly: item.isReadonly ? '1' : '0',  // 只读
          isHistory: item.isHistory ? '1' : '0'      // 历史存储
        }));
      });
    },
    /** 重置导入物模型查询参数 */
    resetImportQuery() {
      this.importQuery = {
        name: null,
        type: null
      };
    },
    /** 处理导入物模型选择变化 */
    handleImportSelectionChange(selection) {
      this.importSelection = selection;
    },
    /** 取消导入物模型 */
    cancelImport() {
      this.importOpen = false;
      this.resetImportQuery();
    },
    /** 返回列表 */
    goBack() {
      this.$router.push({ path: '/iot/product' });
    }
  },
  /** 监听启用授权的变化 */
  watch: {
    'form.isAuthRequired'(newVal) {
      if (newVal === 1) {
        // 如果启用授权，重置授权列表
        this.authList = [];
      }
    },
    // 监听路由参数变化
    '$route'(to, from) {
      const id = to.query.id;
      if (id) {
        // 重新获取产品详情
        this.getInfo(id);
      } else {
        // 重置表单
        this.reset();
      }
    }
  }
};
</script>

<style scoped>
.model-container,
.auth-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  margin-top: 15px;
}

.model-header,
.auth-header {
  margin-bottom: 20px;
}

.bottom-control {
  margin-top: 20px;
  text-align: center;
}

.main-tabs {
  margin-top: 15px;
}

:deep(.el-tabs__header) {
  background-color: #fff;
  margin: 0 0 15px 0;
  padding: 0;
  position: relative;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
  margin-bottom: 0;
}

:deep(.el-tabs__nav) {
  border: none;
}

:deep(.el-tabs__item) {
  height: 48px;
  line-height: 48px;
  font-size: 14px;
  color: #606266;
  padding: 0 25px;
  transition: all 0.3s;
  position: relative;
}

:deep(.el-tabs__item:hover) {
  color: var(--el-color-primary);
}

:deep(.el-tabs__item.is-active) {
  color: var(--el-color-primary);
  font-weight: 500;
}

:deep(.el-tabs__item.is-active:after) {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 3px;
  background: var(--el-color-primary);
  border-radius: 3px;
}

:deep(.el-tabs__nav-wrap::after) {
  display: none;
}

:deep(.el-tabs__content) {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-select) {
  width: 100%;
}

/* 移除边框卡片样式相关的代码 */
:deep(.el-tabs--border-card) {
  border: none;
  box-shadow: none;
}

:deep(.el-tabs--border-card > .el-tabs__header) {
  background: transparent;
  border: none;
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item) {
  border: none;
  margin: 0;
}

:deep(.el-tabs--border-card > .el-tabs__content) {
  border: none;
}

.el-dialog__body {
  padding: 20px 40px;
}

/* 新增按钮样式 */
.model-header .el-button {
  margin-right: 10px;
}

.model-header .el-button [class^="el-icon-"] {
  margin-right: 5px;
}

.model-search {
  padding: 10px 0;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.model-search .el-form-item {
  margin-bottom: 0;
}

.dialog-footer {
  padding: 20px;
  text-align: center;
  border-top: 1px solid #eee;
}

.top-right-btns {
  text-align: right;
  padding: 0 0 8px 0;
}

.top-right-btns .el-button {
  margin-left: 8px;
  font-size: 13px;
  padding: 8px 15px;
}

.top-right-btns .el-button [class^="el-icon-"] {
  margin-right: 3px;
  font-size: 12px;
}
</style> 